*************************************************
********Prepare shapefile and maps data**********
*************************************************

* directory definitions 
	
	project, doinfo
	global pdir "`r(pdir)'"							// the project's main dir.
	global dofile "`r(dofile)'"						// do-file's stub name
	global data_original = "$pdir/data_original"  //data directory for coded data 
	global data_coded = "$pdir/data_coded"  //data directory for coded data 
	global figures = "$pdir/results/figures"  //data directory for figures
	global tables = "$pdir/results/tables"  //data directory for tables

* 
	// report any data we create previously and we do need here: 
	project, uses("$data_coded/placebased_regional.dta")
	
//
	* get shapefile of Italy, prepare and merge with data from Campante	
	project, relies_on("$data_original/Shapefile/Limiti_2016_ED50_g/Com2016_ED50_g/Com2016_ED50_g.shp")

	shp2dta using "$data_original/Shapefile/Limiti_2016_ED50_g/Com2016_ED50_g/Com2016_ED50_g", database("$data_coded/itdb") coordinates("$data_coded/itcoord") genid(id) gencentroids(coord)
	use "$data_coded/itdb", clear
	
	rename PRO_COM comune_id
	
	tempfile shapefile
	save `shapefile'
	
	merge 1:1 comune_id using "$data_coded/placebased_regional.dta"
	drop _merge 
	*
	keep id x_coord y_coord COD_REG COD_CM COD_PRO comune_id km_to_ugs referendum_no
	
	gen ugs_yn = 1 if km_to_ugs == 0 
	replace ugs_yn = 0 if km_to_ugs > 0
	
	lab var km_to_ugs "distance to closest UGS (in km)"
	lab var ugs_yn "UGS station (0,1)"
	
	save "$data_coded/placebased_mapdata.dta", replace

*
	// also produce figure 2b: 
	drop _all
	import delimited "$data_coded/events_comune.csv", clear

	*import meetup data, clear and save temporary
	foreach w of varlist n_total-wn_posttreat {
		replace `w'="0" if `w'=="NA"
		destring `w', replace
	}
	
	foreach w of varlist n_total-wn_posttreat {
		gen log_`w'=log(`w'+1)
	}
	
	*there are duplicate comunes in the data: 
	duplicates tag comune_id, gen(dup)
	
	tempfile meetup
	save `meetup'

	// open geocoded italy data: 
	use "$data_coded/itdb.dta", clear 

	rename PRO_COM comune_id
	
	merge 1:1 comune_id using "`meetup'", gen(_merge_meetup)

	**
	gen treated=0
	replace treated=1 if n_total>=1

	save "$data_coded/placebased_m5s_mapdata.dta", replace

* 
	// report any data we create with this do file: 
	project, creates("$data_coded/placebased_mapdata.dta")
	project, creates("$data_coded/placebased_m5s_mapdata.dta")
	project, creates("$data_coded/itdb.dta")
	project, creates("$data_coded/itcoord.dta")



	